"use strict";
const Koa = require('koa');
const websockify = require('koa-websocket');
const app = websockify(new Koa());
const logger = require('log4js').getLogger('app');
const Router = require('koa-router');
const serve = require('koa-static-cache');
const log = require('koa-log4js-base');
log.configure('workstation');
const bodyParser = require('koa-bodyparser-base');
const session = require('koa-session');
const path = require('path');
const render = require('koa-art-template');
let a = {};

// 中间件
// 模板引擎
render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.html',
  debug: true
});
// session
app.keys = ["workstation-1541746020234"];
app.use(session({
  key: "workstation:sess", // cookie key
  maxAge: 1800000, // session 有效期: 30(min)
  renew: true // 保持持久状态
}, app)); // 配置 session
app.use(log.init()); // 日志记录
app.use(serve('./public',{gzip:true})); // 静态资源
app.use(bodyParser()); // post 请求参数

// 路由
const appRouter = new Router();
appRouter.use('/workstation/product', require('./routes/prod').routes());
appRouter.use('/workstation', require('./routes/index').routes());
// 以下接口都需要进行登录验证
appRouter.use(async (ctx, next) => {
  if(ctx.session.tel) { // session 有缓存态
    await next();
  } else { // session没有, 验证 cookie
    if(ctx.cookies.get('wsSignTel')) { // 已经登录
      ctx.session.signTel = ctx.cookies.get('wsSignTel');
      await next();
    } else { // 进入登录页
      ctx.body = { code: -1, errmsg: 'not login' };
    }
  }
});
appRouter.use('/workstation/tactics', require('./routes/tactics').routes());
app.use(appRouter.routes()).use(appRouter.allowedMethods());

app.ws.use(require('./routes/websocket').routes()); // websocket
module.exports = app;
